from selenium import webdriver
from selenium.webdriver.common.by import By
import time, os


class Page(object):
    '''基础类'''
    login_url = 'http://www.126.com'

    def __init__(self, selenium_driver, baseurl=login_url):
        self.base_url = baseurl
        self.driver = selenium_driver
        self.timeout = 30

    def on_page(self):
        return self.driver.current_url == (self.base_url + self.url)

    def _open(self, url):
        url = self.base_url + url
        self.driver.get(url)
        assert self.on_page(), 'Did not land on %s' % url

    def open(self):
        self._open(self.url)

    def find_element(self, *loc):
        return self.driver.find_element(*loc)


class LoginPage(Page):
    '''126邮箱登录页面模型'''
    url = '/'
    # 定位器
    username_loc = (By.NAME, 'email')
    password_loc = (By.NAME, 'password')
    submit_loc = (By.ID, 'dologin')

    # Action
    def type_username(self, username):
        self.find_element(*self.username_loc).send_keys(username)

    def type_password(self, password):
        self.find_element(*self.password_loc).send_keys(password)

    def submit(self):
        self.find_element(*self.submit_loc).click()


def test_user_login(driver, username, password):
    '''测试用户名密码登录'''
    login_page = LoginPage(driver)
    login_page.open()
    driver.implicitly_wait(5)
    ifm = driver.find_element_by_id('x-URS-iframe')
    driver.switch_to.frame(ifm)
    login_page.type_username(username)
    login_page.type_password(password)
    login_page.submit()


def main():
    try:
        chromedriver = "C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"  # 浏览器驱动位置
        os.environ["webdriver.chrome.driver"] = chromedriver
        driver = webdriver.Chrome(chromedriver)
        username = 'lichunmei55'
        password = 'li19911014'
        test_user_login(driver, username, password)
        time.sleep(3)
        assert (driver.title == '网易邮箱6.0版'), '登录失败'
    finally:
        driver.quit()


if __name__ == "__main__":
    main()
